<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateRoleAPIRequest;
use App\Http\Requests\API\UpdateRoleAPIRequest;
use App\Models\Role;
use App\Repositories\RoleRepository;
use App\Repositories\MenuRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Support\Facades\DB;
use Response;
use Illuminate\Support\Facades\Auth;

/**
 * Class RoleController
 * @package App\Http\Controllers\API
 */

class RoleAPIController extends AppBaseController
{
    /** @var  RoleRepository */
    private $roleRepository;
    private $menuRepository;

    public function __construct(RoleRepository $roleRepo,MenuRepository $menuRepo)
    {
        $this->roleRepository = $roleRepo;
        $this->menuRepository = $menuRepo;
    }

    /**
     * Display a listing of the Role.
     * GET|HEAD /roles
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->roleRepository->pushCriteria(new RequestCriteria($request));
        $this->roleRepository->pushCriteria(new LimitOffsetCriteria($request));
        $roles = $this->roleRepository->withCount('users')->paginate($request->limit);
        return $this->sendResponse($roles->toArray(), '获取角色成功');
    }

    public function lists(Request $request)
    {
        $roles = $this->roleRepository->all();
        return $this->sendResponse($roles->toArray(), '获取角色列表成功');
    }

    /**
     * Store a newly created Role in storage.
     * POST /roles
     *
     * @param CreateRoleAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateRoleAPIRequest $request)
    {
        $input = $request->all();
        $intpu['guard_name'] = 'api';
        $roles = $this->roleRepository->create($input);
        // 菜單添加
        if(!empty($input['menu'])  && $roles){
            $roles->menus()->attach($input['menu']);
        }
        // 添加停車點
        if(!empty($input['park'])  && $roles){
            $menu_relation = [];
            foreach ($input['park'] as $val) {
                $tmp = [];
                $tmp['role_id'] = $roles->id;
                $tmp['park_id'] = ($val);
                $menu_relation[] = $tmp;
            }
            $p = DB::table("role_has_park")->insert($menu_relation);
        }
        return $this->sendResponse($roles->toArray(), '添加角色成功');
    }

    public function store_bak(CreateRoleAPIRequest $request)
    {
        $input = $request->all();
        $intpu['guard_name'] = 'api';
        DB::beginTransaction();
        $roles = $this->roleRepository->create($input);
        // 菜單添加
        if(!empty($input['menu'])  && $roles){
            $menu_relation = [];
            foreach ($input['menu'] as $val) {
                $tmp = [];
                $tmp['role_id'] = $roles->id;
                $tmp['menu_id'] = $val;
                $menu_relation[] = $tmp;
            }
            $f = DB::table("role_has_menu")->insert($menu_relation);
            if(!$f){
                DB::rollback();
                return $this->sendError('操作失敗');
            }
        }
        // 添加停車點
        if(!empty($input['park'])  && $roles){
            $menu_relation = [];
            foreach ($input['park'] as $val) {
                $tmp = [];
                $tmp['role_id'] = $roles->id;
                $tmp['park_id'] = ($val);
                $menu_relation[] = $tmp;
            }
            $p = DB::table("role_has_park")->insert($menu_relation);
            if(!$p){
                DB::rollback();
                return $this->sendError('操作失败');
            }
        }
        DB::commit();
        return $this->sendResponse($roles->toArray(), '添加角色成功');
    }

    /**
     * Display the specified Role.
     * GET|HEAD /roles/{id}
     *
     * @param  int $id
     * @Param  Request $request
     *
     * @return Response
     */
    public function show($id,Request $request)
    {
        /** @var Role $role */
        $this->roleRepository->pushCriteria(new RequestCriteria($request));
        $role = $this->roleRepository->with('users')->findWithoutFail($id);
        if (empty($role)) {
            return $this->sendError('角色不存在');
        }
        $menu = $role->menus;
        $menu_id = array_column(obj2arr($menu),'id');
        $role = $role->toArray();
        // 操作权限
        $menu_res = $this->menuRepository->findWhereIn("id", $menu_id);
        $menus = make_tree($menu_res, 'id', 'pid', '_child', 0);
        $role['menus'] = $menus;
        $role['menu_ids'] = implode(',',$menu_id);

        // 数据权限
        $park = DB::table("role_has_park")->where("role_id",$role['id'])->get();
        $park = obj2arr($park);
        $role['park'] = $park;
        return $this->sendResponse($role, '查询角色成功');
    }

    /**
     * Update the specified Role in storage.
     * PUT/PATCH /roles/{id}
     *
     * @param  int $id
     * @param UpdateRoleAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateRoleAPIRequest $request)
    {
        $input = $request->all();
        $intpu['guard_name'] = 'api';
        /** @var Role $role */
        $role = $this->roleRepository->findWithoutFail($id);

        if (empty($role)) {
            return $this->sendError('角色不存在');
        }
        $role = $this->roleRepository->update($input, $id);

        // 菜單添加
        if(isset($input['menu'])  && $role){
            $role->menus()->sync($input['menu']);
        }
        // 添加停車點
        DB::table("role_has_park")->where("role_id",$id)->delete();
        if(isset($input['park'])  && $role){
            $menu_relation = [];
            foreach ($input['park'] as $val) {
                $tmp = [];
                $tmp['role_id'] = $id;
                $tmp['park_id'] = $val;
                $menu_relation[] = $tmp;
            }
            $p = DB::table("role_has_park")->insert($menu_relation);
        }
        return $this->sendResponse($role->toArray(), '更新角色成功');
    }

    /**
     * Remove the specified Role from storage.
     * DELETE /roles/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var Role $role */
        $role = $this->roleRepository->findWithoutFail($id);

        if (empty($role)) {
            return $this->sendError('角色不存在');
        }
        if ($role->name == env('ROOT_KEY') || $id == 159) {
            return $this->sendError('此为最高权限，拒绝删除');
        }
        DB::beginTransaction();
        $f = $role->delete();
        if($f){
            $p = DB::table("role_has_park")->where("role_id",$id)->delete();
            $m = DB::table("role_has_menu")->where("role_id",$id)->delete();
        } else {
            DB::rollback();
            return $this->sendError('操作失敗');
        }
        DB::commit();
        return $this->sendResponse($id, '删除角色成功');
    }
}
